package cn.com.basespringboot.security;

import cn.com.basespringboot.service.UserService;
import cn.com.basespringboot.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 登录专用类
 * 自定义类，实现了UserDetailsService接口，用户登录时调用的第一类
 *
 */
@Service
@Slf4j
public class CustomUserService implements UserDetailsService {
    @Resource
    UserService userService;
    @Resource
    PasswordEncoderCheck passwordEncoderCheck;
    /**
     * 登陆验证时，通过username获取用户的所有权限信息
     * 并返回UserDetails放到spring的全局缓存SecurityContextHolder中，以供授权器使用
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //在这里可以自己调用数据库，对username进行查询，看看在数据库中是否存在
        UserVo user = userService.getUserByName(username);
        log.info("登录用户名" + username);
        if (user == null) {
            throw new UsernameNotFoundException("没有找到");
        }
        log.info("数据库密码" + user.getPassword());
        UserDetailsCheck myUserDetail = new UserDetailsCheck();
        myUserDetail.setUsername(username);
        myUserDetail.setPassword(passwordEncoderCheck.encode(user.getPassword()));
        return myUserDetail;
    }
}
